<template>
  <div class="tab-dialog-box pos-abs">
    <el-tabs v-model="activeTab" :before-leave="onTabChange">
      <el-tab-pane label="密码策略" name="passwordPolicy">
        <div class="tab-content-box pos-abs">
          <el-form
            :model="passwordPolicy"
            label-width="130px"
            :size="defaultFormItemSize"
            class="setting-form"
          >
            <!-- 密码定期更新 -->
            <el-form-item label="密码定期更新">
              <el-switch v-model="passwordPolicy.passwordExpired" />
            </el-form-item>
            <template v-if="passwordPolicy.passwordExpired">
              <el-form-item label="更新周期">
                <el-input v-model.number="passwordPolicy.updateInterval" type="number">
                  <template slot="append">天</template>
                </el-input>
              </el-form-item>
            </template>

            <!-- 密码强度限制 -->
            <el-form-item label="密码强度限制">
              <el-switch v-model="passwordPolicy.passwordComplexity" />
            </el-form-item>
            <template v-if="passwordPolicy.passwordComplexity">
              <el-form-item class="rule-form-item">
                <div class="rule-item">
                  <el-checkbox v-model="passwordPolicy.minLengthEnabled">最小长度</el-checkbox>
                  <el-input
                    style="width: 146px"
                    v-model.number="passwordPolicy.minLength"
                    type="number"
                  >
                    <template slot="append">位</template>
                  </el-input>
                </div>
                <div class="rule-list">
                  <el-checkbox v-model="passwordPolicy.includeDigit">包含数字</el-checkbox>
                  <el-checkbox v-model="passwordPolicy.includeLowerCase">包含小写字母</el-checkbox>
                  <el-checkbox v-model="passwordPolicy.includeUpperCase">包含大写字母</el-checkbox>
                  <el-checkbox v-model="passwordPolicy.includeSpecialChar">包含字符</el-checkbox>
                </div>
              </el-form-item>
            </template>

            <!-- 禁用旧密码 -->
            <el-form-item label="禁用旧密码">
              <el-switch v-model="passwordPolicy.banOldPassword" />
            </el-form-item>
            <template v-if="passwordPolicy.banOldPassword">
              <el-form-item label="禁用个数">
                <el-input v-model.number="passwordPolicy.banOldPasswordCount" type="number">
                  <template slot="append">个</template>
                </el-input>
              </el-form-item>
            </template>

            <!-- 修改初始密码提醒 -->
            <el-form-item label="修改初始密码提醒">
              <el-switch v-model="passwordPolicy.modifyInitPassword" />
            </el-form-item>

            <!-- 新用户默认密码 -->
            <el-form-item label="新用户默认密码">
              <el-input v-model="passwordPolicy.initPassword" show-password />
            </el-form-item>

            <!-- 保存按钮 -->
            <el-form-item>
              <el-button
                :size="defaultFormItemSize"
                type="primary"
                @click="savePasswordPolicy"
                :loading="loading"
                >保存设置</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>

      <el-tab-pane label="登录策略" name="loginPolicy">
        <div class="tab-content-box pos-abs">
          <el-form
            :model="loginPolicy"
            label-width="120px"
            :size="defaultFormItemSize"
            class="setting-form"
          >
            <!-- 排他登录 -->
            <el-form-item label="排他登录">
              <el-switch v-model="loginPolicy.excludeLogin" />
              <div class="error-handle-desc">开启后同一账号只能在一处登录</div>
            </el-form-item>

            <!-- 超时登出 -->
            <el-form-item label="超时登出">
              <el-input v-model.number="loginPolicy.loginTimeout" type="number">
                <template slot="append">分钟</template>
              </el-input>
            </el-form-item>

            <!-- 密码错误次数 -->
            <el-form-item label="密码错误次数" class="no-margin-bottom">
              <el-input v-model.number="loginPolicy.passwordErrorCount" type="number">
                <template slot="append">次</template>
              </el-input>
            </el-form-item>
            <!-- 错误处理方式 -->
            <el-form-item :class="{ 'no-margin-bottom': loginPolicy.delayLoginWhenError }">
              <div class="error-handle-desc">
                输入密码错误将进行处理，设置3以下值表示不启动该功能
              </div>
              <el-radio-group v-model="loginPolicy.delayLoginWhenError">
                <el-radio :label="false">账号锁定</el-radio>
                <el-radio :label="true">延时登录</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- 延迟时间 -->
            <el-form-item
              :class="{ 'no-margin-bottom': !loginPolicy.delayLoginWhenError }"
              label="延迟时间"
              v-if="loginPolicy.delayLoginWhenError"
              style="margin-left: 60px"
            >
              <el-input v-model.number="loginPolicy.delayLoginTime" type="number">
                <template slot="append">分钟</template>
              </el-input>
            </el-form-item>

            <!-- 保存按钮 -->
            <el-form-item class="login-save-btn">
              <el-button
                :size="defaultFormItemSize"
                type="primary"
                @click="saveLoginPolicy"
                :loading="loading"
                >保存设置</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { SysConfController } from '@/api';

export default {
  name: 'formSysConf',
  data() {
    return {
      activeTab: 'passwordPolicy',
      loading: false,
      // 密码策略数据
      passwordPolicy: {
        passwordExpired: false,
        updateInterval: 90,
        passwordComplexity: false,
        minLengthEnabled: false,
        minLength: 8,
        includeDigit: false,
        includeLowerCase: false,
        includeUpperCase: false,
        includeSpecialChar: false,
        banOldPassword: false,
        banOldPasswordCount: 3,
        modifyInitPassword: false,
        initPassword: '123456'
      },
      // 登录策略数据
      loginPolicy: {
        excludeLogin: false,
        loginTimeout: 30,
        passwordErrorCount: 5,
        delayLoginWhenError: false,
        delayLoginTime: 30
      }
    };
  },
  methods: {
    // 加载配置数据
    async loadConfData(confCode) {
      try {
        this.loading = true;
        const res = await SysConfController.getSysConf(this, { confCode });

        if (res.data?.conf) {
          if (confCode === 'passwordPolicy') {
            const pwdPolicy = JSON.parse(res.data.conf);
            Object.assign(this.passwordPolicy, pwdPolicy);
          } else {
            const loginPol = JSON.parse(res.data.conf);
            Object.assign(this.loginPolicy, loginPol);
          }
        }
      } catch (error) {
        console.error(`加载${confCode === 'passwordPolicy' ? '密码' : '登录'}策略配置失败:`, error);
        this.$message.error(`加载${confCode === 'passwordPolicy' ? '密码' : '登录'}策略配置失败`);
      } finally {
        this.loading = false;
      }
    },

    // 保存密码策略
    async savePasswordPolicy() {
      try {
        await this.$confirm('确认要保存密码策略配置吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        this.loading = true;
        await SysConfController.updateSysConf(this, {
          sysConfDto: {
            confCode: 'passwordPolicy',
            conf: JSON.stringify(this.passwordPolicy)
          }
        });
        this.$message.success('密码策略保存成功');
      } catch (error) {
        if (error !== 'cancel') {
          console.error('保存密码策略失败:', error);
          this.$message.error('保存密码策略失败');
        }
      } finally {
        this.loading = false;
      }
    },

    // 保存登录策略
    async saveLoginPolicy() {
      try {
        await this.$confirm('确认要保存登录策略配置吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });

        this.loading = true;
        await SysConfController.updateSysConf(this, {
          sysConfDto: {
            confCode: 'loginPolicy',
            conf: JSON.stringify(this.loginPolicy)
          }
        });
        this.$message.success('登录策略保存成功');
      } catch (error) {
        if (error !== 'cancel') {
          console.error('保存登录策略失败:', error);
          this.$message.error('保存登录策略失败');
        }
      } finally {
        this.loading = false;
      }
    },

    // Tab切换处理
    async onTabChange(newTab) {
      if (newTab === this.activeTab) return true;
      await this.loadConfData(newTab);
      return true;
    }
  },
  mounted() {
    this.loadConfData('passwordPolicy');
  }
};
</script>

<style lang="scss" scoped>
.pos-abs {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.tab-dialog-box {
  padding: 0 !important;
  margin: 0 !important;

  ::v-deep .el-tabs__header {
    margin-bottom: 0;
    background-color: white;
    border-top: 1px solid #e8e8e8;
  }

  ::v-deep .el-tabs__content {
    position: absolute;
    top: 44px;
    left: 0;
    right: 0;
    bottom: 0;
  }

  ::v-deep .el-tabs__nav-wrap::after {
    display: none;
  }

  ::v-deep .el-tabs__item {
    height: 44px;
    line-height: 44px;
  }

  ::v-deep .el-tabs__nav-wrap {
    padding-left: 24px;
  }

  ::v-deep .el-tabs__content {
    overflow: hidden;
  }

  .tab-content-box {
    display: flex;
    margin: 16px;
    flex-direction: column;
    background-color: #fff;
    padding: 24px;
    border-radius: 2px;
    overflow: auto;
  }
}

.no-margin-bottom {
  margin-bottom: 10px !important;
}

.error-handle-desc {
  color: #999;
  font-size: 13px;
}

.setting-form {
  max-width: 600px;

  ::v-deep .el-form-item {
    margin-bottom: 24px;
  }

  ::v-deep .el-input {
    width: 240px;

    .el-input-group__append {
      background-color: #fff;
      padding: 0 10px;
    }
  }

  ::v-deep .el-switch {
    margin-right: 8px;
  }

  ::v-deep .el-radio-group {
    .el-radio {
      margin-right: 24px;
      &:last-child {
        margin-right: 0;
      }
    }
  }
}

.rule-form-item ::v-deep .el-form-item__content {
  display: flex;
  align-items: start;
  flex-direction: column;
}

.rule-item {
  display: flex;
  align-items: center;
  margin-bottom: 16px;

  .el-checkbox {
    margin-right: 16px;
  }
}

.rule-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
</style>
